package com.szsanshan.station.datacollector.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.szsanshan.station.datacollector.entity.FuelRecord;
import com.szsanshan.station.datacollector.entity.GunStatusRecord;
import com.szsanshan.station.datacollector.entity.StationNozzleRecord;
import com.szsanshan.station.datacollector.entity.StationNozzleStatus;
import com.szsanshan.station.datacollector.util.PetrolSignUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

/**
 * @author xiaotong
 */
@Service
public class PetrolDataService {

    private static final String UPLOAD_URL = "http://pinghu-pos.szsanshan.com/api/fuel-record/";
    private static final String sendFuelRecordsUrl = UPLOAD_URL + "addFuelRecords";
    private static final String sendGunStatusRecordsUrl = UPLOAD_URL + "addGunStatusRecords";
    private static final String latestFuelRecordIdUrl = UPLOAD_URL + "latestFuelRecordId";
    private static final String toShiftTimeUrl = UPLOAD_URL + "getControlShiftTime";
    private static final String shiftDoneUrl = UPLOAD_URL + "controlShiftDone";
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Value("${sanshan.appid}")
    private String APPID;

    @Value("${sanshan.appkey}")
    private String APPKEY;

    @Value("${station}")
    private String stationId;

    /**
     * 发送加油记录
     *
     * @param dataList
     * @return
     */
    public boolean sendFuelRecords(List<StationNozzleRecord> dataList) {
        List<FuelRecord> fuelRecordList = new ArrayList<>();
        for (StationNozzleRecord item : dataList) {
            logger.info("@sendFuelRecords,item={}", item);
            FuelRecord record = new FuelRecord();
            // 流水号
            record.setId(item.getId());
            // 油站ID
            record.setStationId(Integer.valueOf(stationId));
            // 油机金额
            record.setAmount(item.getNozmny());
            // 油枪号
            record.setGunNo(item.getNozno());
            // 加油升数
            record.setLitre(item.getNozqty());
            // 油机单价
            record.setPrice(item.getNozprice());
            // 加油员
            record.setOperator(item.getJiayouyuan());
            //
            record.setStartTime(DateUtil.format(item.getBegintime(), "yyyy-MM-dd HH:mm:ss"));
            // 加油结束时间
            record.setEndTime(DateUtil.format(item.getEndtime(), "yyyy-MM-dd HH:mm:ss"));
            // 油品简称
            record.setFuelName(item.getOilshortname());
            // 油枪期末数
            record.setGunEndNum(item.getNoztotalend());
            fuelRecordList.add(record);
        }
        if (fuelRecordList.size() > 0) {
            // 发送到服务器
            TreeMap<String, String> signMap = getSignMap(JSONUtil.toJsonStr(fuelRecordList));
            String res = HttpRequest.post(sendFuelRecordsUrl).body(JSONUtil.toJsonStr(signMap)).execute().body();
            logger.info("油机数据上传结果:{}", res);
            if (StrUtil.isNotEmpty(res) && JSONUtil.isJson(res)) {
                JSONObject jsonObject = JSONUtil.parseObj(res);
                if (jsonObject.getInt("code") == 200) {
                    StringBuilder ids = new StringBuilder();
                    for (FuelRecord fuelRecord : fuelRecordList) {
                        ids.append(fuelRecord.getId()).append(",");
                    }
                    logger.info("petrol sended: {}", ids.toString());
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 发送加油状态
     *
     * @param dataList
     * @return
     */
    public boolean sendStatusRecords(List<StationNozzleStatus> dataList) {
        List<GunStatusRecord> gunStatusRecordList = new ArrayList<>();
        for (StationNozzleStatus item : dataList) {
            GunStatusRecord record = new GunStatusRecord();
            record.setStationId(stationId);
            record.setAmount(item.getCurramount());
            record.setLitre(item.getCurrnum());
            record.setGunNo(item.getGunno());
            gunStatusRecordList.add(record);
        }
        if (gunStatusRecordList.size() > 0) {
            // 发送到服务器
            TreeMap<String, String> signMap = getSignMap(JSONUtil.toJsonStr(gunStatusRecordList));
            String res = HttpRequest.post(sendGunStatusRecordsUrl).body(JSONUtil.toJsonStr(signMap)).execute().body();
            if (StrUtil.isNotEmpty(res) && JSONUtil.isJson(res)) {
                JSONObject jsonObject = JSONUtil.parseObj(res);
                if (jsonObject.getInt("code") == 200) {
                    logger.info("petrol status send success, size={}", gunStatusRecordList.size());
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取最新加油记录ID
     *
     * @return
     */
    public String latestFuelRecordId() {
        FuelRecord fuelRecord = new FuelRecord();
        fuelRecord.setStationId(Integer.valueOf(stationId));
        TreeMap<String, String> signMap = getSignMap(JSONUtil.toJsonStr(fuelRecord));
        String res = HttpRequest.post(latestFuelRecordIdUrl).body(JSONUtil.toJsonStr(signMap)).execute().body();
        if (StrUtil.isNotEmpty(res) && JSONUtil.isJson(res)) {
            JSONObject jsonObject = JSONUtil.parseObj(res);
            if (jsonObject.getInt("code") == 200) {
                return jsonObject.getStr("data");
            }
        }
        return "-1";
    }

    /**
     * 签名验证
     *
     * @param reqData
     * @return
     */
    private TreeMap<String, String> getSignMap(String reqData) {
        TreeMap<String, String> signMap = new TreeMap<>();
        signMap.put("appId", APPID);
        signMap.put("appKey", APPKEY);
        signMap.put("nonceStr", IdUtil.fastSimpleUUID());
        signMap.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
        signMap.put("reqData", reqData);
        String sign = PetrolSignUtils.sign(signMap);
        signMap.put("sign", sign);
        return signMap;
    }

    /**
     * 获取要中控交班的时间
     *
     * @return
     */
    public String getToShiftTime() {
        FuelRecord fuelRecord = new FuelRecord();
        fuelRecord.setStationId(Integer.valueOf(stationId));
        TreeMap<String, String> signMap = getSignMap(JSONUtil.toJsonStr(fuelRecord));
        String res = HttpRequest.post(toShiftTimeUrl).body(JSONUtil.toJsonStr(signMap)).execute().body();
        if (StrUtil.isNotEmpty(res) && JSONUtil.isJson(res)) {
            JSONObject jsonObject = JSONUtil.parseObj(res);
            if (jsonObject.getInt("code") == 200) {
                return jsonObject.getStr("data");
            }
        }
        return "";
    }

    /**
     * 通知服务器交班成功
     *
     * @param time
     * @return
     */
    public boolean sendShiftDone(String time) {
        FuelRecord fuelRecord = new FuelRecord();
        fuelRecord.setStationId(Integer.valueOf(stationId));
        TreeMap<String, String> signMap = getSignMap(JSONUtil.toJsonStr(fuelRecord));
        String res = HttpRequest.post(shiftDoneUrl).body(JSONUtil.toJsonStr(signMap)).execute().body();
        if (StrUtil.isNotEmpty(res) && JSONUtil.isJson(res)) {
            JSONObject jsonObject = JSONUtil.parseObj(res);
            if (jsonObject.getInt("code") == 200) {
                return true;
            }
        }
        return false;
    }
}
